import java.io.PrintWriter;
import java.util.*;

public class XMLParser {
	private Stack<String> stack;
	private String data;
	private int tag;
	
	public XMLParser(){
		stack=new Stack<String>();
		data="";
		tag=0;
	}
	
	//method seperates tokens and inserts them into a stack
	public void parseTokens(Scanner file){
		PrintWriter output=null;
		output=FileUtils.PrintWriterOpen("zlog1");
		
		String input="";
		output.print("XMLParser:  enter checkValidXML");
		
		while(file.hasNext()){
			
			input=file.next();
			
			
			//pushes open tag into stack and increments tag
			if(isOpenTag(input))
			{
				
				stack.push(input);
				tag++;
				
			}
			//pops all tokens associated with the corresponding open tag and prints them to the file
			else if(isCloseTag(input))
			{
				//pops all data tokens
				while(!isOpenTag(stack.peek())){
					data=""+stack.pop()+" "+data;		//assigns data to string, reversed to account for the way objects exit a stack
					
				}
				//pops the open tag associated with the close tag
				if(isOpenTag(stack.peek())){
					String open=stack.pop();
					
					data=" tag "+tag+" '"+open.substring(1,open.length()-1)+"':  '"+data;
					
					//prints a number of X's equal to the value of tag
					for(int i=0; i<tag; i++){
						data="X "+data;
					}
					data="\nXMLParser: "+data+"'";
				
				}
				output.print(data);
				data="";
					
				
					tag--;
					
				
			}
			else {			//data tokens
				stack.push(input);
				
			}
			
			
			
			
			
			
		}
		output.println("\nXMLParser:  leave checkValidXML");
		output.println("Main:  XML is valid");
		output.println("Main:  no more data, terminate");
		output.close();
		
	}
	//determines if a String is a closing tag
	public boolean isCloseTag(String info){
		if(info.charAt(0)=='<' && info.charAt(1)=='/' && info.charAt(info.length()-1)=='>'){
			return true;
		}
		else{
			return false;
		}
		
	}
	//determines if a String is a opening tag
	public boolean isOpenTag(String info){
		if(info.charAt(0)=='<' && info.charAt(info.length()-1)=='>' && info.charAt(1)!='/'){
			return true;
		}
		else{
			return false;
		}
	}
	
	//calls parseTokens method, called in Driver class
public boolean checkValidXML(Scanner inFile){
	this.parseTokens(inFile);
	
	return true;
	}

}
